<template>
  <FromSearch :searchParams="queryParams" :formRenderData="formRenderData" @open-form-page="openFormPage" @handle-query="handleQuery" @reset-query="resetQuery">
    <template #buttonSlot>
      <el-button type="success" plain @click="openShareDialog('create')">
          <Icon icon="ep:share" class="mr-5px" /> 分享
        </el-button>
    </template>
    </FromSearch>
  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="tableData" :stripe="true" >
      <el-table-column label="序号" align="center">
        <template  #default="scope">
            {{ scope.$index + 1}}
        </template>
      </el-table-column>
      <el-table-column
        v-for="(item, index) in tableHeader" 
        :key="index" 
        :label="item.columnComment" 
        :show-overflow-tooltip="item.schemaType !='picture-upload'"
        align="center"
        :prop="item.columnName"
         >
         <template #default="scope">
            <!-- 字段展示 -->
            <span v-if="!uploadData.includes(item.schemaType)">{{ scope.row[item.columnName] }}</span>
            <!-- 对上传接口的字段做特殊展示 -->
            <div v-if="uploadData.includes(item.schemaType)">
              <!-- uploadData 1是图片 2是文件 -->
               <div v-if="item.schemaType === uploadData[0]" >
                <el-image 
                  style="margin-right: 2px;" 
                  v-for="(v, i) in JSON.parse(scope.row[item.columnName])" 
                  @click="imagePreview(baseURL + v.url)" 
                  :key="i" :src="baseURL + v.url" 
                  class="h-30px w-30px" />
               </div>
               <div v-if="item.schemaType === uploadData[1]" >
                <a v-for="(v, i) in JSON.parse(scope.row[item.columnName])" class="link-a" :href="baseURL+v.url" type="text" :key="i">
                 {{ v.name }}<br/>
                </a>
               </div>
            </div>
          </template>
         </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="200px">
        <template #default="scope">
          <el-button link type="primary" @click="openFormPage('update', scope.row.id)">
            编辑
          </el-button>
          <el-button link type="primary" @click="openDetailPage('detail',scope.row.id)">
            详情
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
:total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getTableList" />
  </ContentWrap>
   
  <!-- 表单分享弹窗 -->
  <FormQrShare ref="formQrShareRef" :formName="formName"/>
  </template>

<script setup lang="ts">
import { InstanceApi } from '@/api/infra/instance/index'
import { useRouter } from 'vue-router'
import FromSearch from './FormSearch.vue'
import qs from 'qs'
import FormQrShare from './FormQrShare.vue'
import { formRenderRoute, uploadData } from '../config'
import { createImageViewer } from '@/components/ImageViewer'
// 使用 process.env.VUE_APP_BASE_URL (Vite 使用 import.meta.env)
const baseURL = import.meta.env.VITE_PROXY_TARGET_MAIN
defineOptions({ name: 'Instance' })

const { t } = useI18n() // 国际化
const router = useRouter()
const message = useMessage() // 消息弹窗
const tableData: any = ref()
const tableHeader: any = ref([])
const loading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const total = ref(0) // 列表的总页数
const currentRouteName = ref()
const currentRoutePath = ref()
const queryParams: any = reactive({
  pageNo: 1,
  pageSize: 10,
  id: undefined,
  formCode: undefined,
})
/** 搜索按钮操作 */
const handleQuery = (data) => {
  for(var key in data) {
    queryParams[key] = data[key]
  }
  queryParams.pageNo = 1
  getTableList()
}

/** 添加操作 */
const openFormPage = (type: string, id?: number) => {
  routerJump(type, id)
}
/** 详情操做 */
const openDetailPage = (type: string, id: number) => {
  routerJump(type, id)
}
/** 跳转路由函数 */
const routerJump = (type: string, id?: number) => {
  router.push({
    path: formRenderRoute,
    query: {
      id: id,
      type: type,
      formCode: queryParams.formCode,
      currentRouteName: currentRouteName.value,
      currentRoutePath: currentRoutePath.value
    }
  })
}
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await InstanceApi.deleteInstance(id, formCodeValue.value)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getTableList()
  } catch { }
}


// 列表展示
// const pictureData: any = ref([])
// const fileData = ref([])
const formCodeValue: any = ref('')
const getTableList = async () => {
  loading.value = true
  try {
    queryParams.formCode = formCodeValue.value
    let res = await InstanceApi.getInstaceList(queryParams)
    tableData.value = res.list
    total.value = res.total
    console.log(tableData.value, tableHeader.value,'formRenderData')

  } finally {
    loading.value = false
  }
}
/**
 * 打开分享弹窗
 */
 const formQrShareRef = ref()
const openShareDialog = (type) => {
  const query = qs.stringify({
    type: type,
    formCode:  formCodeValue.value
  })
  const mainOut = '/main-out'
  const url = window.location.origin + mainOut + formRenderRoute + "?" + query
  formQrShareRef.value.open(url)
}
const formRenderData: any = ref()
const formName = ref()
onMounted(async () => {
  const path = router.currentRoute.value.path
  currentRouteName.value = router.currentRoute.value.meta.title
  currentRoutePath.value = router.currentRoute.value.path
  const routerPath = path.split('/')
  const formCode = routerPath[routerPath.length - 1].replace(/formconstruct\_/g, '')
  const params: any = {
    formCode: formCode
  }
  formName.value = `${router.currentRoute.value.meta.title}`
  formCodeValue.value = formCode

  let res = await InstanceApi.getListColumnDO(params)
  formRenderData.value = res
  //表头数据获取
  res.map((item => {
    tableHeader.value.push({
      columnName: item.columnName,
      columnComment: item.columnComment,
      schemaType: item.schemaType
    })
  }))
  getTableList()
})
const resetQuery = () => {
  queryParams.searchFieldVos = []
  queryParams.createTime = undefined
  handleQuery({})
}
// 预览点击
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

</script>

<style scoped>
.link-a {
  display: inline-block;
  width: 100%;
  overflow: hidden;
  color: #409eff;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
